package controlador;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import javax.sql.DataSource;

public class Temporizador implements Runnable {

	String mensaje;
	String destinos;
	String fecha;// "2010-09-10 15:29"
	String shortcode;
	String password;
	String server;
	String nombres;
	boolean personalizado;

	public Temporizador(String mensaje, String destinos, String nombres,
			String fecha, String shortcode, String password, String server,
			boolean personalizado) {
		super();
		this.mensaje = mensaje;
		this.destinos = destinos;
		this.nombres = nombres;
		this.fecha = fecha;
		this.shortcode = shortcode;
		this.password = password;
		this.server = server;
		this.personalizado = personalizado;
	}

	public void run() {
		// TODO Auto-generated method stub
		System.out.println("Hilo(" + fecha + "):Inicio");
		boolean esperando = true;

		do {

			String DATE_FORMAT_NOW = "dd/MM/yyyy HH:mm";
			Calendar cal = Calendar.getInstance();
			SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
			String hora = sdf.format(cal.getTime());

			Date programada = null;
			try {
				programada = sdf.parse(fecha);
			} catch (ParseException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			Date ahora = new Date();

			// System.out.println(hora);

			// System.out.println("P:"+programada.toString());
			// System.out.println("A:"+ahora.toString());

			if (programada.after(ahora) || programada.equals(ahora)) {

				esperando = false;

				String[] dest = destinos.split(",");
				String[] nom = null;
				if (personalizado) {
					nom = nombres.split(";");
				}

				for (int i = 0; i < dest.length; i++) {

					try {
						// Construct data
						String data = URLEncoder.encode("shortcode", "UTF-8")
								+ "=" + URLEncoder.encode(shortcode, "UTF-8");
						data += "&" + URLEncoder.encode("password", "UTF-8")
								+ "=" + URLEncoder.encode(password, "UTF-8");
						data += "&" + URLEncoder.encode("destinos", "UTF-8")
								+ "=" + URLEncoder.encode(dest[i], "UTF-8");
						if (personalizado) {
							data += "&"
									+ URLEncoder.encode("contenido", "UTF-8")
									+ "="
									+ URLEncoder.encode(
											nom[i] + ", " + mensaje, "UTF-8");
						} else {
							data += "&"
									+ URLEncoder.encode("contenido", "UTF-8")
									+ "=" + URLEncoder.encode(mensaje, "UTF-8");
						}

						// Send data
						URL url = new URL(server + "/brokerSend");
						URLConnection conn = url.openConnection();
						conn.setDoOutput(true);
						OutputStreamWriter wr = new OutputStreamWriter(
								conn.getOutputStream());
						wr.write(data);
						wr.flush();

						// Get the response
						BufferedReader rd = new BufferedReader(
								new InputStreamReader(conn.getInputStream()));
						String line;
						while ((line = rd.readLine()) != null) {
							System.out.println("Hilo(" + fecha + "):" + line);
						}
						wr.close();
						rd.close();
					} catch (Exception e) {
						System.out.println("Hilo(" + fecha + "):Error");
					}
				}

			}

			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} while (esperando);

	}

}
